/*
 * Timer.cpp
 *
 *  Created on: 17 déc. 2011
 *      Author: M. Alexandre (malexand314@gmail.com)
 */

#include "Timer.h"

using namespace Framework;

#include <ctime>

Timer::Timer() : ObserverSubject()
{
    pthread_mutex_init(&m_timeMutex, NULL);
    m_iTimeRemaining = -1;
    m_iLastTimestamp = 0;

    startThread();
}

Timer::~Timer()
{
    pthread_mutex_destroy(&m_timeMutex);
}

int Timer::getTimeRemaining()
{
    int iTimeRemaining = 0;

    pthread_mutex_lock(&m_timeMutex);
    iTimeRemaining = m_iTimeRemaining;
    pthread_mutex_unlock(&m_timeMutex);

    return iTimeRemaining;
}

void Timer::startTimer(int _iSeconds)
{
    pthread_mutex_lock(&m_timeMutex);
    m_iTimeRemaining = _iSeconds;
    m_iLastTimestamp = time(NULL);
    pthread_mutex_unlock(&m_timeMutex);
}

void Timer::stopTimer()
{
    pthread_mutex_lock(&m_timeMutex);
    m_iTimeRemaining = 0;
    pthread_mutex_unlock(&m_timeMutex);
}

void Timer::updateState()
{
    pthread_mutex_lock(&m_timeMutex);
    int iLastTimeRemaining = m_iTimeRemaining;
    pthread_mutex_unlock(&m_timeMutex);

    if(iLastTimeRemaining > 0)
    {
        time_t iTimestamp = time(NULL);
        int iNewTimeRemaining = 0;

        iNewTimeRemaining = iLastTimeRemaining - (iTimestamp - m_iLastTimestamp);

        m_iLastTimestamp = iTimestamp;

        if(iNewTimeRemaining != iLastTimeRemaining)
        {
            pthread_mutex_lock(&m_timeMutex);
            m_iTimeRemaining = iNewTimeRemaining;
            pthread_mutex_unlock(&m_timeMutex);
            notify();
        }
    }
}

void Timer::runThread()
{
    while(1)
    {
        updateState();
    }
}
